package com.gzc.just.play.last.war.gateserver.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.common.net.NetUtils;
import com.gzc.just.play.last.war.gateserver.GateNettyServer;
import com.gzc.just.play.last.war.protobuf.cs.cstogs.CSToGS;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@MessageHandler(name = "OrderPostToGCHandler", serverTypes = MessageHandler.ServerType.GATE_SERVER)
public class OrderPostToGCHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(OrderPostToGCHandler.class);

    @Autowired
    private GateNettyServer gateNettyServer;

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        CSToGS.OrderPostToGC order = null;
        if (message instanceof byte[]) {
            order = CSToGS.OrderPostToGC.parseFrom((byte[]) message);
        } else if (message instanceof CSToGS.OrderPostToGC) {
            order = (CSToGS.OrderPostToGC) message;
        }

        if (order == null) {
            logger.error("Failed to parse OrderPostToGC message");
            return;
        }

        // 转发消息给客户端
        for (CSToGS.OrderPostToGC.UserNetInfo userInfo : order.getUsernetinfoList()) {
            int nsid = userInfo.getGcnid();
            ChannelHandlerContext clientCtx = gateNettyServer.getClientConnection(nsid);
            if (clientCtx != null && clientCtx.channel().isActive()) {
                // 直接转发 byte[] payload，避免二次序列化
                // 注意：这里需要重新封装成Netty消息格式，或者直接使用 NetUtils 发送
                // order.getOthermsg() 是 ByteString，需要转换
                byte[] payload = order.getOthermsg().toByteArray();
                int msgId = order.getOthermsgid();
                
                // 这里我们假设payload已经是序列化好的 protobuf 字节流
                // NetUtils.sendMsg 会再次封装 [Len][MsgId][Body]
                // 这里的 payload 仅仅是 Body
                NetUtils.sendMsg(clientCtx.channel(), msgId, payload);
                logger.debug("Forwarded message {} to client {}", msgId, nsid);
            } else {
                logger.warn("Client {} not found or disconnected, cannot forward message {}", nsid, order.getOthermsgid());
            }
        }
    }

    @Override
    public int getMessageId() {
        return 24581; // CSToGS.MsgID.eMsgToGSFromCS_OrderPostToGC
    }

    @Override
    public String getName() {
        return "OrderPostToGCHandler";
    }

    @Override
    public Logger getLogger() {
        return logger;
    }
}
